import Layout from '@/views/Layout.vue'
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores/user'
import routerMap from './routerMap'
import { refreshToken } from '@/api/userApi'
let initBool = true
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'main',
      component: Layout
    },
    {
      path: '/login',
      name: 'login',
      meta: {
        nologin: true
      },
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      meta: {
        nologin: true
      },
      component: () => import('@/views/Register.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/Error.vue')
    }
  ],
})
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const store = useUserStore()
  await refreshToken()
  if (store.userInfo) {
    const store = useUserStore()
    routerMap.forEach((item) => {
      if (item.meta.role.includes(store.userInfo.role)) {
        router.addRoute("main", item)
      }
    })
  }
  if (!store.accessToken && !to.meta.nologin) {
    next({ name: "login" })
    NProgress.done()
    return
  }
  if (initBool) {
    initBool = false
    next(to.path)
    NProgress.done()
    return
  }
  next()
  NProgress.done()
})
router.afterEach(() => {
  NProgress.remove()
})
export default router
